package com.jdcjk.base.view;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.mvp.presenter.impl.MvpBasePresenter;
import com.mvp.view.impl.MvpFragment;

/**
 * Created by dong on 2016/12/1.
 * Fragment基础实现类
 */
public abstract class BaseFragment<P extends MvpBasePresenter> extends MvpFragment<P> implements View.OnClickListener, View.OnLongClickListener {
    //我们自己的Fragment需要缓存视图
    protected View viewContent; //缓存视图
    private boolean isInit;
    private FragmentViewClickListener fragmentViewClickListener;
    private FragmentViewLongClickListener onFragmentViewLongClickListener;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (viewContent == null) {
            viewContent = inflater.inflate(getLayoutId(), container, false);
            initContentView(viewContent);
        }

        //判断Fragment对应的Activity是否存在这个视图
        ViewGroup parent = (ViewGroup) viewContent.getParent();
        if (parent != null) {
            //如果存在,那么我就干掉,重写添加,这样的方式我们就可以缓存视图
            parent.removeView(viewContent);
        }
        return viewContent;
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        if (!isInit) {
            this.isInit = true;
            initData();
        }
    }

    @Override
    public void onStart() {
        super.onStart();
        refreshView();
    }

    public void setFragmentViewClickListener(FragmentViewClickListener fragmentViewClickListener) {
        this.fragmentViewClickListener = fragmentViewClickListener;
    }

    public void setOnFragmentViewLongClickListener(FragmentViewLongClickListener onFragmentViewLongClickListener) {
        this.onFragmentViewLongClickListener = onFragmentViewLongClickListener;
    }

    @Override
    public void onClick(View view) {
        if (fragmentViewClickListener != null) {
            fragmentViewClickListener.onFragmentViewClickListener(view);
        }
    }

    @Override
    public boolean onLongClick(View view) {
        return onFragmentViewLongClickListener != null && onFragmentViewLongClickListener.onFragmentViewLongClickListener(view);
    }

    @Override
    public P bindPresenter() {
        return null;
    }

    public abstract int getLayoutId();

    public abstract void initContentView(View viewContent);

    public void initData() {
    }

    public void refreshView() {
    }

}
